using UnityEngine;
using UnityEngine.AI;

public class Enemy : RoleInfo
{

    public bool isDead = false; // 是否已经死亡
    public Transform player; // 玩家对象
    public float alertRange = 10f; // 警戒范围
    public float attackRange = 2f; // 攻击范围
    public float timeBetweenAttacks = 1f; // 攻击间隔
    public GameObject bulletPrefab; // 子弹预制体
    public Transform firePoint; // 发射点
    public float fireRate = 1f; // 射击频率
    private NavMeshAgent agent; // 导航代理
    private float nextAttackTime = 0f; // 下一次攻击的时间
    private bool isInAttackRange = false; // 是否在攻击范围内

    new void Start()
    {
        base.Start();
        agent = GetComponent<NavMeshAgent>();
        coll = GetComponent<Collider>();
    }

    void Update()
    {
        if (isDead || !player) return; // 死亡后不能动
        float distanceToPlayer = Vector3.Distance(player.position, transform.position);

        if (distanceToPlayer <= alertRange)
        {
            if (distanceToPlayer <= attackRange)
            {
                // 如果玩家在攻击范围内，停止移动并射击
                isInAttackRange = true;
                agent.isStopped = true;

                // 更新敌人的朝向
                FacePlayer();

                if (Time.time >= nextAttackTime)
                {
                    Attack();
                    nextAttackTime = Time.time + timeBetweenAttacks;
                }
            }
            else
            {
                // 如果玩家在警戒范围内但不在攻击范围内，移动到玩家附近
                isInAttackRange = false;
                agent.isStopped = false;
                agent.SetDestination(player.position);

                // 设置动画状态为移动
                anim.SetInteger("state", 1);
            }
        }
        else
        {
            // 如果玩家不在警戒范围内，停止移动
            isInAttackRange = false;
            agent.isStopped = true;

            // 设置动画状态为闲置
            anim.SetInteger("state", 0);
        }
    }

    void FacePlayer()
    {
        // 计算玩家相对于敌人的方向
        Vector3 direction = (player.position - transform.position).normalized;
        // 设置敌人的朝向
        Quaternion lookRotation = Quaternion.LookRotation(direction);
        transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 10f);
    }

    void Attack()
    {
        // 实例化子弹
        GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
        // 可以在这里添加其他逻辑，例如给子弹添加速度或方向
    }

    public override void die()
    {
        anim.SetTrigger("die"); // 播放死亡动画
        isDead = true; // 标记为死亡
        coll.enabled = false; // 关闭碰撞
        anim.SetLayerWeight(1, 0); // 假设图层索引为 0
    }
}